/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package cn.edu.nju.software.AtoClient;


import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 *
 * @author zf
 */
@WebServlet(name="NewServlet", urlPatterns={"/NewServlet"})
public class LoginServlet extends HttpServlet {


        private String driver;
	private String url;
	private String user;
	private String password;
        private LoginServlet ls = new LoginServlet();//use the obj to call methods


    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException, SQLException {
        response.setContentType("text/html;charset=UTF-8");
        String name = request.getParameter("name");//get contents from the request
        String passwordGet = request.getParameter("password");

        //handle in the DB with  name and password to ensure whether the name and password are valid
        PrintWriter out = response.getWriter();//outputStream
        try {

            out.write(ls.handleLogin(name, passwordGet));//out return the name to client
            out.flush();
           
        } finally { 
            out.close();
        }


    } 
public String handleLogin (String name,String passwd) throws SQLException{
            driver = "com.mysql.jdbc.Driver";
            url = "jdbc:mysql://localhost/test";
            user = "root";
            password = "NICAIA";

          try {
                  Class.forName(driver);
                  Connection conn = DriverManager.getConnection(url, user, password);
                  Statement statement = conn.createStatement();
                String sql = "select * from goodslist " + "where name='" + name +"and password="+passwd;
                ResultSet rs = statement.executeQuery(sql);
                if(rs==null)
                return "false";
                else
                return "true";
        } catch (ClassNotFoundException ex) {
                ex.printStackTrace();
        }catch (SQLException e){
                e.printStackTrace();
        }
            return null;

       }
}
  